#!/usr/bin/env python
###############################################################################
# unzip.py: Unzip Utility
###############################################################################
# Copyright (C) 2010 CERN
#
# Author: Rohit Yadav <rohityadav89 AT gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
###############################################################################

import sys
import zipfile
import os
import os.path
import getopt
from logger import *

class unzip:
    """ Unzip gives you utility to unzip a .zip file
    To use, first make an object, to turn on verbose mode pass True 
    unzipper = unzip(True)
    
    Set source and destination
    zipsource = "test.zip"
    zipdest = "."

    Call extract() to extract zip valid zip file
    unzipper.extract(zipsource, zipdest)"""

    def __init__(self, verbose = False):
        self.verbose = verbose
        
    def extract(self, file, dir):
        if not dir.endswith(':') and not os.path.exists(dir):
            os.mkdir(dir)

        zf = zipfile.ZipFile(file)

        # create directory structure to house files
        self._createstructure(file, dir)

        num_files = len(zf.namelist())

        # extract files to directory structure
        for i, name in enumerate(zf.namelist()):

            #if self.verbose == True:
            #    logger("ZipTool", "Extracting: " + name)

            if not name.endswith('/'):
                outfile = open(os.path.join(dir, name), 'wb')
                outfile.write(zf.read(name))
                outfile.flush()
                outfile.close()

    def _createstructure(self, file, dir):
        self._makedirs(self._listdirs(file), dir)

    def _makedirs(self, directories, basedir):
        """ Create any directories that don't currently exist """
        for dir in directories:
            curdir = os.path.join(basedir, dir)
            if not os.path.exists(curdir):
                os.mkdir(curdir)

    def _listdirs(self, file):
        """ Grabs all the directories in the zip structure
        This is necessary to create the structure before trying
        to extract the file to it. """
        zf = zipfile.ZipFile(file)

        dirs = []

        for name in zf.namelist():
            if name.endswith('/'):
                dirs.append(name)

        dirs.sort()
        return dirs

def test():
  p = unzip(True)

  source = "test.zip"
  dest = "."

  p.extract(source, dest)

if __name__ == "__main__":
  test()
